﻿using Company.Core.Config;
using Company.Core.Helper;
using Company.Hardware;
using Company.Hardware.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 无人值守地磅称重系统.Interfaces;

namespace 无人值守地磅称重系统.Services
{
    public class HardwareManager : IHardwareManager
    {
        public bool Initialized { get ; set; }

        private IConfigManager ConfigManager { get; }

        private ICamera Camera { get; }

        private IConfigService ConfigService { get; }

        private IScale Scale;

        private ICameraIce CameraIce { get; }

        public HardwareManager(IConfigManager configManager, 
            IScale scale,
            ICamera camera, 
            IConfigService configService,
            ICameraIce cameraIce)
        {
            ConfigManager = configManager;
            Camera = camera;
            ConfigService = configService;
            Scale = scale;
            CameraIce = cameraIce;
        }

        public async Task<bool> InitializeAsync(IntPtr intPtr)
        {
            if (Initialized) throw new Exception("硬件重复初始化");
            var t = await Task.Factory.StartNew(() =>
            {
                HardwareConfig config = ConfigService.HardwareConfig;
                bool result = true;

                // 初始化称重仪表
                if (!Scale.Initialized)
                {
                    Scale.MessageChanged += (message) => Log.Error(message);
                    result |= Scale.Init(config.PortName, config.BaudRate);
                    result |= Scale.Open();
                }

                // 初始化海康威视网络摄像头
                if (!Camera.Initialized)
                {
                    Camera.MessageChanged += (message) => Log.Error(message);
                }

                result |= Camera.Init(config.DvrIPAddress, config.DvrPortNumber, config.DvrUserName, config.DvrPassword, intPtr);
                result |= Camera.Open();

                // 初始化Ice_ipc网络摄像头
                if (!CameraIce.Initialized)
                {
                    CameraIce.MessageChanged += (message) => Log.Error(message);
                }
                result |= CameraIce.OpenPreview(config.IceIPAddress, 1, 1, (uint)intPtr, null, new IntPtr());

                return result;
            });
            Initialized = true;
            return t;
        }

        public void Close()
        {
            Scale.Close();
            Camera.Close();
            CameraIce.Close();
        }
    }
}
